package com.conversationboard.controller;

import java.io.IOException;
import java.security.Principal;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.model.Search;
import com.conversationboard.model.SearchResult;
import com.conversationboard.model.User;

@WebServlet(name = "SearchByDateControllerServlet", urlPatterns = "/SearchByDateControllerServlet")
public class SearchByDateControllerServlet extends HttpServlet {

	private static final long serialVersionUID = 598257066466087077L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		String date = (String) request.getParameter("date").trim();

		if (!date.matches("^[0-9]{4}-[0-9]{2}-[0-9]{2}$")) {
			request.setAttribute("message", "Please enter a date in the format YYYY-MM-DD, e.g. 2000-12-31, for 31st December 2000.");
			RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/messagepage.jsp");
			dispatcher.forward(request, response);
			return;
		}

		try {

			Principal principal = request.getUserPrincipal();
			String loginId = null;

			if (principal != null) {
				loginId = principal.getName();
			}

			User user = User.get(loginId);

			Search search = new Search();
			List<SearchResult> searchResults = search.dateSearch(date);

			request.setAttribute("user", user);
			request.setAttribute("searchresults", searchResults);

			RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/searchresultsbydate.jsp");
			dispatcher.forward(request, response);

		} catch (SQLException e) {
			throw new ServletException(e);
		} catch (ServletException e) {
			throw new ServletException(e);
		} catch (IOException e) {
			throw new ServletException(e);
		}

	}

}
